﻿/*--------------------------------------------------------------
 * Author : Shine K Velayudhan 
 ---------------------------------------------------------------*/
using System;
using System.Reflection;
using System.Runtime.Remoting.Messaging;

namespace IQN.Logging
{
    internal class LoggerServerSink : IMessageSink
    {
        private IMessageSink next;
        public LoggerServerSink(IMessageSink next)
        {
            this.next = next;
        }
        public IMessageCtrl AsyncProcessMessage(IMessage msg, IMessageSink replySink)
        {
            return null;
        }
        public IMessageSink NextSink
        {
            get { return this.next; }
        }
        public IMessage SyncProcessMessage(IMessage msg)
        {
            DateTime start = DateTime.Now;
            IMessage actualMethod = next.SyncProcessMessage(msg);
            if (msg is IMethodMessage)
            {
                InjectAspect(msg as IMethodMessage, start);
            }
            return actualMethod;
        }
        private void InjectAspect(IMethodMessage msg, DateTime start)
        {
            MethodBase methodInfo = msg.MethodBase;
            if (methodInfo.IsConstructor) return;

            object[] customAttributes = methodInfo.GetCustomAttributes(true);
            foreach (Attribute attr in customAttributes)
            {
                if(attr.GetType() == typeof(LoggerMethodAttribute))
                {
                    LoggerMethodAttribute logAttr = attr as LoggerMethodAttribute;
                    logAttr.StartTime = start;
                    logAttr.EndTime = DateTime.Now;
                    logAttr.ClassName = msg.TypeName.Substring(0, msg.TypeName.IndexOf(' ')-2);
                    logAttr.MethodName = msg.MethodName;
                    logAttr.Log(msg);
                }
            }
        }
    }
}
